import EXIF from './exif.js'

/**
 *对图片旋转处理
 *
 * @param {*} img
 * @param {*} direction 旋转方向，left和right
 * @param {*} canvas
 * @returns
 */
function rotateImg(img, direction, canvas) {
    //最小与最大旋转方向，图片旋转4次后回到原方向
    var min_step = 0;
    var max_step = 3;

    //img的高度和宽度不能在img元素隐藏后获取，否则会出错
    if (img == null) {
        return;
    }
    var height = img.height;
    var width = img.width;

    var step = 2;
    if (step == null) {
        step = min_step;
    }
    if (direction == 'right') {
        step++;
        //旋转到原位置，即超过最大值
        step > max_step && (step = min_step);
    } else {
        step--;
        step < min_step && (step = max_step);
    }
    //旋转角度以弧度值为参数
    var degree = step * 90 * Math.PI / 180;
    var ctx = canvas.getContext('2d');
    switch (step) {
        case 0:
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0);
            break;
        case 1:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, 0, -height);
            break;
        case 2:
            canvas.width = width;
            canvas.height = height;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, -height);
            break;
        case 3:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, 0);
            break;
    }
}

/**
 *将base64转换成file对象
 *
 * @param {*} dataurl 图片的base64编码
 * @param {*} filename file对象类型
 * @returns
 */
function dataURLtoFile(dataurl, filename = 'file') {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let suffix = mime.split('/')[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
    })
}

/**
 *旋转手机拍照变横后的照片
 *
 * @param {*} file 传入当前的input type=file
 * @param {*} callback 回调函数，照片旋转后执行的事件
 * @returns
 */
function rotatePhoto(file, callback) {
	var base64;
    var Orientation = null;
    if (file) {
        console.log("正在上传,请稍后...");
        var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式
        if (!rFilter.test(file.type)) {
            return;
        }

        //获取照片方向角属性，用户旋转控制
        EXIF.getData(file, function () {
            EXIF.getAllTags(this);
            Orientation = EXIF.getTag(this, 'Orientation');
        });

        var oReader = new FileReader();
        oReader.onload = function (e) {
            var image = new Image();
            image.src = e.target.result;
            image.onload = function () {
                var expectWidth = this.naturalWidth;
                var expectHeight = this.naturalHeight;
                if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) {
                    expectWidth = 800;
                    expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
                } else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1200) {
                    expectHeight = 1200;
                    expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
                }
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                canvas.width = expectWidth;
                canvas.height = expectHeight;
                ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
                var u = navigator.userAgent;
                if (Orientation != "" && Orientation != 1) {
                    //alert('旋转处理');
                    switch (Orientation) {
                        case 6: //需要顺时针（向左）90度旋转
                            console.log('需要顺时针（向左）90度旋转');
                            rotateImg(this, 'left', canvas);
                            break;
                        case 8: //需要逆时针（向右）90度旋转
                            console.log('需要逆时针（向右）90度旋转');
                            rotateImg(this, 'right', canvas);
                            break;
                        case 3: //需要180度旋转
                            console.log('需要180度旋转');
                            rotateImg(this, 'right', canvas); //转两次
                            rotateImg(this, 'right', canvas);
                            break;
                    }
                }
                 base64 = canvas.toDataURL("image/jpeg", 0.8);
                var type = 'jpeg';
                var fixtype = function (type) {
                    type = type.toLocaleLowerCase().replace(/jpg/i, 'jpeg');
                    var r = type.match(/png|jpeg|bmp|gif/)[0];
                    return 'image/' + r;
                };
                base64 = base64.replace(fixtype(type), 'image/jpeg');
                // 将base64转换成file对象
                var base64ToFile = dataURLtoFile(base64);
                //把已经旋转过的图片file对象通过回调函数返回
                // callback(base64ToFile)
                callback(base64)
            };
        };
        oReader.readAsDataURL(file);
    }
	return base64
}


export default{
	dataURLtoFile,
	rotatePhoto
}